package com.hx.resource.controller;

import com.hx.resource.domain.FileInfo;
import com.hx.resource.service.IFileInfoService;
import com.hx.resource.utils.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class FileUploadControllers {
    @Autowired
    private AliyunOSSUtils fileUploadService;
    @Autowired
    private IFileInfoService iFileInfoService;

    @PostMapping("uploads")
    public Map<String,String> upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String type = fileName.substring(fileName.lastIndexOf("."));
        String types = "";
        if (type.equals(".png") || type.equals(".jpg") || type.equals(".jpeg")) types = "1";
        else if (type.equals(".mp4") || type.equals(".wmv")) types = "2";
        else types = "0";
        long size = file.getSize();
        byte[] bytes = file.getBytes();
        String md5 = DigestUtils.md5DigestAsHex(bytes);
        FileInfo  fileInfo = new FileInfo();
        fileInfo.setMd5(md5);
        FileInfo fileInfos = iFileInfoService.selectByMd5(md5);
        System.out.println(fileInfos);
        Map<String,String> map = new HashMap<>();
        map.put("fileName",fileName);
        map.put("md5",md5);
        map.put("fileType",types);
        map.put("fileSize",String.valueOf(size));
        if (fileInfos!=null) map.put("httpPath",fileInfos.getHttpPath());
        else map.put("httpPath","https://" + fileUploadService.uploadFileInputSteam(file));
        return  map;
    }


}